package com.gzgy.ustore.api.util;

import javax.annotation.PostConstruct;

import org.apache.commons.lang.ArrayUtils;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

/**
 * 用户文件上传验证类
 * 
 * @author kelvin.tie
 */
public class MultipartFileValidator {

	//set default file size 1M
	private final static long MAX_SIZE = 1024 * 1024 ;

	/**
	 * 文件大小上限
	 */
	private long maxSize = MAX_SIZE*300;

	/**
	 * 可接受的文件content-type
	 */
	private String[] allowedContentTypes;

	@PostConstruct
	public void afterPropertiesSet() {
		Assert.notEmpty(allowedContentTypes,
						"The content types allowed to be uploaded must contain one at least!");
	}

	/**
	 * 验证上传文件是否合法，如果不合法那么会抛出异常
	 * 
	 * @param file
	 *            用户上传的文件封装类
	 */
	public void validate(MultipartFile file) {
		Assert.notNull(file, "The multipart file is null!");
		//check size
		if (file.getSize() > maxSize)			
			throw new RuntimeException("error.upload--->  The file size ["+file.getSize()+"] uploaded is out of max file size ["+maxSize+"]!");
		//check file type
		if (!ArrayUtils.contains(allowedContentTypes,file.getContentType())){
			throw new RuntimeException("error.upload--->content.not supported The content type '"+file .getContentType()+"' is not a valid content type !");
		}
	}

	/**
	 * 设置文件上传大小上限
	 * 
	 * @param maxSize
	 *            文件上传大小上限
	 */
	public void setMaxSize(long maxSize) {
		this.maxSize = maxSize;
	}

	/**
	 * 设置可接受的文件content-type数组
	 * 
	 * @param allowedContentTypes
	 *            可接受的文件content-type数组
	 */
	public void setAllowedContentTypes(String[] allowedContentTypes) {
		this.allowedContentTypes = allowedContentTypes;
	}

}
